package com.xxbb.chapter_11.dome4_packet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class Server {
    static final int PORT = 9090;
    private static byte[] buf = new byte[1024];

    public static void main(String[] args) {
        //创建数据包对象
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        DatagramSocket dgSocket = null;
        try {
            dgSocket = new DatagramSocket(PORT);
            System.out.println("--服务端已经启动监听--");
            while (true) {
                dgSocket.receive(dp);//启动监听，阻塞程序
                //获取到数据报中的数据，转换为字符串
                String data = new String(dp.getData(), 0, dp.getLength(), StandardCharsets.UTF_8);
                String rcvd = "从地址" + dp.getAddress() + "，端口号：" + dp.getPort() + "，发来的数据：" + data;
                System.out.println(rcvd);
                String echoString = "Echoed:" + data;
                byte[] b = echoString.getBytes();
                //从对方发来的数据报中获取对方的地址和端口号，以及数据再发送给对方
                DatagramPacket packet = new DatagramPacket(b, b.length, dp.getAddress(), dp.getPort());
                dgSocket.send(packet);//给对方发送信息
            }
        } catch (SocketException e) {
            System.out.println("端口被占用："+e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dgSocket != null) dgSocket.close();
        }

    }

}
